import React, { Component } from 'react';
import { connect } from 'dva';
import { produce, Draft } from 'immer';
import { Select, Button, Table, Pagination, message } from 'antd';
import styles from '../infoComponents/commList.css';
import { Statistics } from '@/models/connect';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE } from '@/const';
import { deviceStatisticsEx, deviceKinds } from '@/services/statistics';
import { Dispatch, AnyAction } from 'redux';
import router from 'umi/router';
import DeviceStatistics from './deviceStatistics';
import { isMenuVisible } from '@/utils/utils';
import _ from 'lodash';

const { Option } = Select;
interface commListPsops {
  deviceList?: Statistics;
  longDeviceType?: Statistics;
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
}
interface DetailState {
  filterQueryParams: any;
  kinds: any;
  visible: boolean;
  params: any;
}
class commList extends Component<commListPsops, DetailState> {
  //   constructor(props: commListPsops) {
  //     super(props);
  //   }
  state: DetailState = {
    filterQueryParams: {
      deviceSonTypeNo: undefined, // 资产种类
      deviceTypeNo: undefined, // 资产类别
      pageNum: DEFAULT_PAGE_NUM,
      pageSize: 10,
    },
    params: {
      deviceTypeNo: null,
    },
    visible: true,
  };
  handleChangeType = (e: number) => {
    // 资产种类
    if (!this.state.filterQueryParams.deviceTypeNo) {
      // alert('')
      message.info('请先选择所属类别');
      return;
    } else {
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.filterQueryParams.deviceSonTypeNo = e;
          draft.kinds = draft.filterQueryParams.deviceSonTypeNo;
        }),
      );
    }
    // this.setState(
    //   produce((draft: Draft<DetailState>): void => {
    //     draft.filterQueryParams.deviceSonTypeNo = e;
    //     draft.kinds = draft.filterQueryParams.deviceSonTypeNo;
    //   }),
    // );
  };
  handleChangeCategory = (e: number) => {
    // 资产类别
    console.log(e);
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.deviceTypeNo = e;
        draft.filterQueryParams.deviceSonTypeNo = '';

        draft.params.deviceTypeNo = e;
      }),
    );
    const { dispatch } = this.props;
    if (e) {
      dispatch({ type: 'device/matchChildsByParents', payload: { deviceTypeNo: e } });
    } else {
      dispatch({ type: 'device/clearChildren' });
    }
    // this.deviceKindsSelect();
  };
  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => this.handleFilterQuery(),
    );
  };
  handleStatus = (
    visibleId: number,
    id: string,
    deviceState: string,
    deviceTypeParentNo: string,
    deviceSonTypeNo: string,
  ) => {
    //页面切换
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/deviceVisible',
      payload: {
        visible: visibleId,
        visibleStatus: id,
        deviceState: deviceState,
        deviceTypeParentNo: deviceTypeParentNo + '',
        deviceSonTypeNo: deviceSonTypeNo + '',
      },
    });
  };
  handleFilterQuery = () => {
    // 搜索
    const { dispatch } = this.props;
    dispatch({ type: 'statistics/deviceList', payload: this.state.filterQueryParams });
  };
  download = () => {
    //导出
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/drugListEx',
      payload: {
        params: this.state.filterQueryParams,
        typeApi: deviceStatisticsEx,
        name: '设备统计列表.xlsx',
      },
    });
  };
  deviceKindsSelect = async () => {
    const [err, data] = await deviceKinds(this.state.params);
    if (!err) {
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.kinds = data;
        }),
      );
    }
  };
  async componentWillMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'statistics/longDeviceType' });
    this.handleFilterQuery();
    dispatch({ type: 'device/clearChildren' });
    // this.deviceKindsSelect();
  }
  columns: any = [
    {
      title: '资产类别',
      dataIndex: 'typeName',
      key: 'typeName',
    },
    {
      title: '资产种类',
      dataIndex: 'typeSonName',
      key: 'typeSonName',
    },
    {
      title: '设备总数',
      dataIndex: 'deviceCount',
      key: 'deviceCount',
      render: (text, record) => {
        return (
          <a
            onClick={() =>
              this.handleStatus(1, 'deviceCount', '', record.deviceTypeNo, record.deviceSonTypeNo)
            }
          >
            {text}
          </a>
        );
      },
    },
    {
      title: '设备正常',
      dataIndex: 'deviceNormalCount',
      key: 'deviceNormalCount',
      render: (text, record) => (
        <a
          onClick={() =>
            this.handleStatus(1, 'deviceCount', '1', record.deviceTypeNo, record.deviceSonTypeNo)
          }
        >
          {text}
        </a>
      ),
    },
    {
      title: '设备异常',
      dataIndex: 'deviceFault',
      key: 'deviceFault',
      render: (text, record) => {
        return (
          <a
            onClick={() =>
              this.handleStatus(1, 'deviceFault', '2', record.deviceTypeNo, record.deviceSonTypeNo)
            }
          >
            {text}
          </a>
        );
      },
    },
    {
      title: '设备报警(次)',
      dataIndex: 'deviceAlam',
      key: 'deviceAlam',
      render: (text, record) => {
        return (
          <a
            onClick={() =>
              router.push(`/callpoliceManage/${record.deviceTypeNo}/${record.deviceSonTypeNo}`)
            }
          >
            {text}
          </a>
        );
      },
    },
  ];
  render() {
    const { deviceList = [], longDeviceType = [], childList = [] } = this.props;
    const { kinds } = this.state;
    return this.state.visible ? (
      <div style={{ width: '100%' }} className={styles['deviceCom']}>
        <div
          className={styles['inforAnasy-container-top']}
          style={{ paddingLeft: '0', overflow: 'hidden' }}
        >
          <div className={styles['inforAnasy-container-top-btn']}>
            {isMenuVisible('log:Statistical:exportDc') && (
              <Button
                 type="link"
                 onClick={() => {this.download();}}
              >
                <img src={require('@/assets/images/add.png')} alt="" />
                导出EXCEL
              </Button>
            )}
            <Button
              style={{ float: 'right', marginRight: 0 }}
              type="link"
              onClick={() => {
                const { dispatch } = this.props;
                this.setState({ visible: false });
                dispatch({ type: 'statistics/deviceDetailReturn', payload:'true' });
              }}
            >
              <img src={require('@/assets/images/change.png')} alt="" />
            </Button>
          </div>
          <div style={{ clear: 'both' }}>
            <div
              className={styles['inforAnasy-container-top-input dev-search']}
              style={{ display: 'flex' }}
            >
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>资产类别</span>
                <Select
                  style={{ width: 200 }}
                  allowClear={true}
                  placeholder="请选择资产类别"
                  onChange={this.handleChangeCategory}
                  value={this.state.filterQueryParams.deviceTypeNo}
                >
                  {/* <Option value="">请选择</Option> */}
                  {_.map(longDeviceType, (item: any, index: number) => (
                    <Option key={index} value={item.deviceTypeNo}>
                      {item.deviceTypeName}
                    </Option>
                  ))}
                </Select>
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>资产种类</span>
                <Select
                  allowClear={true}
                  value={this.state.filterQueryParams.deviceSonTypeNo}
                  style={{ width: 200 }}
                  placeholder="请先选择资产类别"
                  onChange={this.handleChangeType}
                >
                  {_.map(childList, (item: any, index: number) => (
                    <Option key={index} value={item.deviceTypeNo}>
                      {item.deviceTypeName}
                    </Option>
                  ))}
                </Select>
              </div>
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.pageNum = 1;
                    }),
                    () => {
                      this.handleFilterQuery();
                    },
                  );
                }}
              >
                搜索
              </Button>
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.deviceSonTypeNo = undefined;
                      draft.filterQueryParams.deviceTypeNo = undefined;
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
        </div>
        <Table
          scroll={{ y: '500px' }}
          pagination={false}
          columns={this.columns}
          dataSource={deviceList.rows}
          rowKey="deviceId"
        />
        {/* <Pagination onChange={this.handlePageChange} total={deviceList.total} /> */}
        <div className="pagination-box">
          <Pagination 
            onChange={this.handlePageChange} 
            defaultCurrent={this.state.filterQueryParams.pageNum}
            current={this.state.filterQueryParams.pageNum}
            total={deviceList.total?deviceList.total:0} 
          />
          <span className="pagination-title-box">
            第{this.state.filterQueryParams.pageNum}/
            {Math.ceil((deviceList.total?deviceList.total:0) / this.state.filterQueryParams.pageSize)}页 共
            {deviceList.total?deviceList.total:0}条
          </span>
        </div>
      </div>
    ) : (
      <DeviceStatistics />
    );
  }
}
export default connect(({ loading, statistics, device }: any) => {
  return {
    loading: loading.effects['statistics/deviceList'],
    deviceList: statistics.deviceList,
    deviceKinds: statistics.deviceKinds,
    longDeviceType: statistics.longDeviceType,
    childList: device.matchChildsByParents,
  };
})(commList);
